<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="券名称" prop="title">
                <el-input
                    v-model="queryParams.title"
                    placeholder="请输入券名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:coupon:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5" style="display:none;">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['business:coupon:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="商户名称" align="left" prop="tenantName" width="180px;"/>
            <el-table-column label="券名称" align="left" prop="title" width="200px;" :show-overflow-tooltip="true"/>
            <el-table-column label="券类型" align="center" prop="title">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.couponType==0">满减券</el-tag>
                    <el-tag  v-if="scope.row.couponType==1">打折券</el-tag>
                    <el-tag  v-if="scope.row.couponType==2">兑换券</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="使用条件" align="center" prop="title" width="210px;" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="scope.row.couponType==0">满{{scope.row.amount}}元，减{{scope.row.reduce}}元</span>
                    <span v-if="scope.row.couponType==1">满{{scope.row.amount}}元，打{{scope.row.discount}}折</span>
                    <span v-if="scope.row.couponType==2">满{{scope.row.amount}}元，免费兑换{{scope.row.exchangeItems}}</span>
                </template>
            </el-table-column>
            <el-table-column label="券有效期" align="center" prop="days" width="200px;">
                <template slot-scope="scope">
                    <span v-if="scope.row.periodType=='0'">自领取日<el-tag>{{scope.row.days}}</el-tag>内有效</span>
                    <span v-if="scope.row.periodType=='1'">{{parseTime(scope.row.startTime, '{y}-{m}-{d}')}} ~ {{parseTime(scope.row.endTime, '{y}-{m}-{d}')}}</span>
                </template>
            </el-table-column>
            <el-table-column label="上架时间" align="center" prop="days" width="200px;">
                <template slot-scope="scope">
                    <span>{{parseTime(scope.row.activityStart, '{y}-{m}-{d}')}} ~ {{parseTime(scope.row.activityEnd, '{y}-{m}-{d}')}}</span>
                </template>
            </el-table-column>
            <!--<el-table-column label="核销方式" align="center">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.mode=='0'">自助核销</el-tag>
                    <el-tag type="warning" v-if="scope.row.mode=='1'">其他</el-tag>
                </template>
            </el-table-column>-->
            <!--<el-table-column label="可用时段" align="center" width="400px;">
                <template slot-scope="scope">
                    <el-tag :key="s.value" v-for="s in scope.row.ss">{{s.label}}</el-tag>
                </template>
            </el-table-column>-->
            <el-table-column label="券总量" align="center">
                <template slot-scope="scope">
                    <el-tag v-show="scope.row.stockType=='0'">不限</el-tag>
                    <el-tag v-show="scope.row.stockType=='1'">{{scope.row.stock}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="消耗积分" align="center" prop="points"/>
            <el-table-column label="上架状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="审核" align="center" prop="audit">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.audit==0">待镇审核</el-tag>
                    <el-tag type="danger" v-if="scope.row.audit==1">已审核</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="领取量" align="center" prop="draw"/>
            <el-table-column label="使用量" align="center" prop="used"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180" >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handleUpdate(scope.row,true)"
                        v-hasPermi="['business:coupon:edit']"
                    >查看
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handleUpdate(scope.row,false)"
                        v-hasPermi="['business:coupon:edit']"
                    >修改
                    </el-button>
                    <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                                 v-hasPermi="['business:coupon:audit']" v-if="scope.row.audit==0">
                        <el-button size="mini" type="text" icon="el-icon-d-arrow-right" v-if="scope.row.audit=='0'">更多</el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleAudit" icon="el-icon-circle-check"
                                              v-hasPermi="['business:coupon:audit']" v-if="scope.row.audit==0">审核
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改券码信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" :disabled="formRead" >
                <el-form-item label="券名称：" prop="title">
                    <el-input v-model="form.title" placeholder="请输入券名称" style="width: 500px;"/>
                </el-form-item>
                <el-form-item label="券原价：" prop="originalPrice">
                    <el-input v-model="form.originalPrice" placeholder="请输入券对应的原商品价值多少元" style="width: 500px;"/>
                </el-form-item>
                <el-form-item label="券商品图：" prop="logo">
                    <image-upload v-model="form.logo" :limit="1"/>
                </el-form-item>
                <el-form-item label="券类型：" prop="couponType" @change="handleCouponType">
                    <el-radio-group v-model="form.couponType">
                        <el-radio :key="type.label" :label="type.label" v-for="type in couponTypes">{{ type.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item  prop="amount" v-show="form.couponType==0">
                    满<el-input v-model="form.amount" placeholder="满多少元" maxlength="40"  style="width: 200px;margin-left: 5px;margin-right: 5px;"/>元，减<el-input v-model="form.reduce" placeholder="减多少元" maxlength="10"  style="width: 200px;margin-left: 5px;margin-right: 5px;"/>元
                </el-form-item>
                <el-form-item  prop="amount" v-show="form.couponType==1">
                    满<el-input v-model="form.amount" placeholder="满多少元" maxlength="40"  style="width: 200px;margin-left: 5px;margin-right: 5px;"/>元，打<el-input v-model="form.discount" placeholder="打多少折" maxlength="10"  style="width: 200px;margin-left: 5px;margin-right: 5px;"/>折
                </el-form-item>
                <el-form-item  prop="amount" v-show="form.couponType==2">
                    满<el-input v-model="form.amount" placeholder="满多少元" maxlength="40"  style="width: 200px;margin-left: 5px;margin-right: 5px;"/>元，免费兑换<el-input v-model="form.exchangeItems" placeholder="某某商品等" maxlength="10"  style="width: 200px;margin-left: 5px;margin-right: 5px;"/>
                </el-form-item>
                <el-form-item label="券有效日期：" prop="periodType">
                    <el-radio-group v-model="form.periodType" @change="handlePeriodType">
                        <el-radio :key="type.label" :label="type.label" v-for="type in periodType">{{ type.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item  prop="days" v-show="dayType=='0'">
                    自领取日起<el-input v-model="form.days" placeholder="" maxlength="10"  style="width: 80px;margin-left: 5px;margin-right: 5px;"/>天内有效（含生效日期含领取当日）
                </el-form-item>
                <el-form-item  prop="exprieStart" v-show="dayType=='1'">
                    <el-date-picker
                        v-model="expireDate.date"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="有效期开始时间"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        end-placeholder="有效期结束时间" @change="expireDateFormat">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="门店核销码：" prop="stores">
                    <el-input placeholder="请输入核销码,不填写则当前门店不参与" v-model="store.code" v-for="store in stores" :key="store.id" style="width:400px;margin-bottom:5px;">
                        <template slot="prepend">{{store.label}}</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="券总量：" prop="stock">
                    <el-radio-group v-model="form.stockType">
                        <el-radio :key="type.label" v-for="type in stockType" :label="type.label">{{type.name}}</el-radio>
                    </el-radio-group>
                    <el-input v-model="form.stock" placeholder="请输入券总量" style="width: 200px;margin-left: 5px;" v-show="form.stockType=='1'"/>
                </el-form-item>
                <el-form-item label="积分数：" prop="points">
                    <el-input v-model="form.points" placeholder="请输入兑换此券需要多少积分" style="width: 200px;margin-left: 5px;"/>
                </el-form-item>
                <el-form-item label="核销方式:" prop="mode">
                    <el-radio-group v-model="form.mode">
                        <el-radio :key="type.label" :label="type.label" v-for="type in modeType">{{ type.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="可用时段:" prop="timeInterals">
                    <el-checkbox-group v-model="form.timeInterals">
                        <el-checkbox :label="week.label" :key="week.label" v-for="week in weeks">{{week.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="上架时间:" prop="activityStart">
                    <el-col :span="20">
                        <el-date-picker
                            v-model="activityDate.date"
                            type="datetimerange"
                            range-separator="至"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            start-placeholder="上架开始时间"
                            end-placeholder="上架结束时间"  @change="activityDateFormat">
                        </el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="企微客服:" prop="wechat" v-show="false" >
                    <el-input v-model="form.wechat" placeholder="请输入企微客服地址" style="width: 500px;"/>
                </el-form-item>
                <el-form-item label="使用说明:" prop="description">
                    <el-input v-model="form.description" type="textarea" placeholder="请输入内容"  :autosize="{ minRows: 5}"/>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" v-if="!formRead">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listCoupon,
    getCoupon,
    delCoupon,
    addCoupon,
    updateCoupon,
    handleStatusChange,
    handleAuditChange
} from "@/api/business/coupon";
import {listStore} from "@/api/business/store";
import {parseWeekText,parseTime} from "@/utils/ruoyi";

export default {

    name: "Coupon",
    data() {
        return {
            isView:false,
            activityDate:{
                date:'',
                startTime:'',
                endTime:'',
            },
            expireDate:{
                date:'',
                startTime:'',
                endTime:'',
            },
            formRead:false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 券码信息表格数据
            couponList: [],
            modeType:[{'name':'自助核销','label':'0'}],//,{'label':'1','name':'其他'}
            stockType:[{'name':'不限','label':'0'},{'label':'1','name':'限制'}],
            couponTypes:[{'name':'满减券','label':0},{'name':'折扣券','label':1},{'name':'换购券','label':2}],
            periodType:[{'label':'0','name':'自领取日起'},{'label':'1','name':'固定有效期'}],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            times:[],
            activityTimes:[],
            dayType:'',
            couponType:'',
            stores:[],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                tenantId: null,
                title: null,
                logo: null,
                periodType: null,
                startTime: null,
                endTime: null,
                days: null,
                total: null,
                mode: null,
                description: null,
                status: null,
            },
            storeQueryVars:{
                status:0,
                pageNum: 1,
                pageSize: 100,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                title: [{required: true, message: "券名称", trigger: "blur"}],
                originalPrice: [{required: true, message: "券原价值", trigger: "blur"}],
                logo: [{required: true, message: "券商品图", trigger: "blur"}],
                amount: [{required: true, message: "门槛金额不能空", trigger: "blur"}],
                points: [{required: true, message: "兑换的积分不能空", trigger: "blur"}],
                activityStart: [{required: true, message: "上架时间不能空", trigger: "blur"}],
            },
            weeks: [
                {'name':"星期日","label":'0'},
                {'name':"星期一","label":'1'},
                {'name':"星期二","label":'2'},
                {'name':"星期三","label":'3'},
                {'name':"星期四","label":'4'},
                {'name':"星期五","label":'5'},
                {'name':"星期六","label":'6'}],


        };
    },
    created() {
        this.getList();
        this.getStores();
    },
    methods: {
        handleCommand(command, row) {
            switch (command) {
                //设置审核
                case "handleAudit":
                    this.handleAudit(row);
                    break;
                default:
                    break;
            }
        },
        getStores() {
            listStore(this.storeQueryVars).then(res=>{
                let stores = res.rows;
                for (let i = 0; i < stores.length; i++) {
                    let s = {'id':'','label':'','code':''};
                    s.id = stores[i].storeId;
                    s.label = stores[i].title;
                    this.stores.push(s);
                }
            });
        },
        handlePeriodType(label) {
            this.dayType = label;
        },
        handleCouponType(label) {
            this.couponType = label;
        },
        /** 查询券码信息列表 */
        getList() {
            this.loading = true;
            listCoupon(this.queryParams).then(response => {
                this.couponList = response.rows;
                for (let lengthKey=0;lengthKey<this.couponList.length;lengthKey++) {
                    let d = this.couponList[lengthKey].timeInteral;
                    var weekText = parseWeekText(d);
                    this.couponList[lengthKey].timeInteral=weekText;
                    this.couponList[lengthKey].ss=weekText;

                }
                this.total = response.total;
                this.loading = false;
            });

        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                couponId: null,
                tenantId: null,
                title: null,
                logo: null,
                timeInterals: ['0','1','2','3','4','5','6'],
                timeInteral:'',
                stores:'',
                periodType: null,
                startTime: null,
                days: "",
                draw: null,
                used: null,
                mode: null,
                wechat: null,
                description: null,
                status: null,
                stockType:null,
                points:null,
                stock:null,
                couponType:null,
                total:null,
                reduce:null,
                discount:null,
                originalPrice:null,
                exchangeItems:null

            };
            this.times=null
            this.activityTimes=null
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.couponId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        activityDateFormat(picker) {
            this.form.activityStart =picker[0].toString();
            this.form.activityEnd = picker[1].toString();
            console.log("activityTimes")
        },
        expireDateFormat(expire) {
            this.form.startTime =expire[0].toString();
            this.form.endTime = expire[1].toString();
            console.log("time")
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.formRead = false;
            this.open = true;
            this.title = "添加券码信息";
            this.form.mode='0';//核销类型
            this.dayType = '0';//券有效期类型
            this.form.periodType = '0';
            this.form.couponType = 0;
            this.form.stockType='0'

        },
        /** 修改按钮操作 */
        handleUpdate(row,isView) {

            this.reset();
            this.formRead = isView;
            const couponId = row.couponId || this.ids
            if (isView) {
                this.title = "查看券码信息";
            }
            else {
                this.title = "修改券码信息";
            }
            getCoupon(couponId).then(response => {
                this.form = response.data;
                this.open = true;
                this.form.periodType = this.form.periodType.toString();
                this.dayType = this.form.periodType.toString();
                this.stores = JSON.parse(this.form.stores);


                if (this.form.periodType==1) {
                    this.expireDate.date=[]
                    this.expireDate.date.push(this.form.startTime)
                    this.expireDate.date.push(this.form.endTime)
                }
                if (this.form.periodType==0 && this.form.days==='0') {
                    this.form.days = '';
                }

                this.activityDate.date=[]
                this.activityDate.date.push(this.form.activityStart);
                this.activityDate.date.push(this.form.activityEnd);
                this.form.mode= this.form.mode.toString();
                this.form.timeInterals = this.form.timeInteral.split(",");
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    //核销码
                    for (let store of this.stores) {
                        if (store.code.trim()=='') {
                            this.$modal.alertError(store.label+'门店核销码不能空');
                            return false;
                        }
                    }
                    //券条件
                    if (this.form.couponType==0 && this.form.reduce.trim()=='') {
                        this.$modal.alertError('满减的金额不能空');
                        return false;
                    }
                    if (this.form.couponType==1 && this.form.discount.trim()=='') {
                        this.$modal.alertError('打折券的折扣不能空');
                        return false;
                    }
                    if (this.form.couponType==2 && this.form.exchangeItems.trim()=='') {
                        this.$modal.alertError('兑换券的兑换物不能空');
                        return false;
                    }
                    //券有效期
                    if (this.form.periodType==0 && (this.form.days==='')) {
                        this.$modal.alertError('券自领取人有效天数不能空');
                        return false;
                    }
                    if (this.form.periodType==1 && this.form.startTime.trim()=='') {
                        this.$modal.alertError('券固定有效期不能空');
                        return false;
                    }
                    //券库存
                    if (this.form.stockType==1 && (this.form.stock=='' || this.form.stock==0 )) {
                        this.$modal.alertError('券的数量不能空或0');
                        return false;
                    }
                    if (this.form.timeInterals.toString().trim()=='') {
                        this.$modal.alertError('券可用时间段不能空');
                        return false;
                    }
                    this.form.timeInteral = this.form.timeInterals.toString();

                    this.form.stores = JSON.stringify(this.stores);

                    if (this.form.couponId != null) {
                        updateCoupon(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                    else {
                        console.log(this.form)

                        //return;
                        addCoupon(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const couponIds = row.couponId || this.ids;
            this.$modal.confirm('是否确认删除券码信息编号为"' + couponIds + '"的数据项？').then(function () {
                return delCoupon(couponIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('business/coupon/export', {
                ...this.queryParams
            }, `coupon_${new Date().getTime()}.xlsx`)
        },
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "禁用";
            this.$modal.confirm('确认要' + text + row.title + '这个优惠券嘛？').then(function () {
                return handleStatusChange(row.couponId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
        handleAudit(row){
            this.$modal.confirm('确认审核这个优惠券嘛？').then(function () {
                return handleAuditChange(row.couponId, 1);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.audit = row.audit === "0" ? "1" : "0";
            });
        }
    }
};
</script>
